<template>
  <div class="most">
    <el-page-header @back="goBack" style="margin-left: -14%;">
    </el-page-header>
    <h2 style="color: #1989fa">{{courseName}}</h2>
    <video :src="videoUrl" controls style="width: 100%; max-width: 800px; height: auto; display: block;" class="vido"></video>
    <div class="author" @click="goTeacher(courseId)">
      <img :src="userurl" style="width: 50px;height: 50px;border-radius:50%;">
      <h3 style="position: absolute;top: 10px;left: 50px; width: 200px">{{nickname}}</h3>
    </div>
    <div v-if="others.length>0" class="momo">
      <h3>相关作品</h3>
      <ul>
        <li v-for="ob in others" :key="ob.id">

          <img :src="ob.courseLogo" style="width: 200px; height: 100px;">
          <span style="position: absolute;width: 300px;color: #333333;">{{ob.introduce}}</span>
          <br/><br/>

        </li>
      </ul>
    </div>

    <div class="overlay">

      <i class="el-icon-video-play">{{ playNumber }}&nbsp;&nbsp;&nbsp;&nbsp;</i>
      <i class="el-icon-star-on">{{ favoriteNumber }}&nbsp;&nbsp;&nbsp;&nbsp;</i>
      <i class="el-icon-chat-dot-round">{{ commentNumber }}</i>
    </div>
    <h3 style="color: #96ccde;width: 800px;">{{introduce}}</h3>
    <div class="blck">
      <span  class="demonstration">课程评价</span>
      <el-rate v-model="value1" ></el-rate>
    </div>
    <button @click="toggleFavorite(courseId)">
      {{ isFavorite ? '取消收藏' : '收藏' }}
    </button>
    <div class="blck">
      <textarea v-model="comment" placeholder="请输入您的评论"></textarea><br/>
      <button @click="submitComment">提交评论</button>
    </div>


    <div class="block" >
      <h3>最新评论：</h3>
      <ul>
        <li v-for="comment in comments" :key="comment.id">
          <img :src="comment.user_head" alt="用户头像" class="mmmg">
          <span class="nickname">{{ comment.nickname }}</span>
          &nbsp;<br/>
          <span class="content">{{ comment.content }}</span>
          &nbsp; &nbsp; &nbsp; &nbsp;<br/>
          <span class="timestamp">{{ comment.createTime }}</span>
          &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button icon="el-icon-circle-check" size="mini" round type="primary" style="width: 70px;height: 30px" @click="praisel(comment.id,comment.praise,)">点赞{{comment.praise}}</el-button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <button v-if="comment.username === username" class="deleteContent" @click="deleteComment(comment.id)">
            删除
          </button>
          <br/>
          ----------------------------------------------
        </li>

      </ul>
    </div>
  </div>
</template>

<script>
// import user from '@/store/modules/user';
import axios from 'axios';
import { Toast } from 'vant';
export default {
  data() {
    return {
      videoUrl: '', // 初始化为空字符串
      userurl:'',
      value1: null,
      courseId:'',
      username:'',
      user_head:'',
      createTime:'',
      comment: '',
      comments: [],
      others:[],
      ob:'',
      praise:'',
      isFavorite: '',
      set:true,
      courseName:'',
      introduce:'',
      nickname:'',
      lecturerName:'',
      username1:'',
      commentNumber:'',
      favoriteNumber:'',
      playNumber:'',
    };
  },
  methods:{
    goBack() {
      this.$router.go(-1);
    },
    toggleFavorite(courseId) {
      // 切换收藏状态
      this.isFavorite=!this.isFavorite
      // 更新 localStorage 中的收藏状态
      let favorites = JSON.parse(localStorage.getItem('favorites')) || [];

      if (this.isFavorite) {
        if (!favorites.includes(courseId)) { // 防止重复添加
          favorites.push(courseId);
        }
      } else {
        // 如果当前是取消收藏状态，则从 favorites 数组中移除
        const indexToRemove = favorites.indexOf(courseId);
        if (indexToRemove !== -1) {
          favorites.splice(indexToRemove, 1);
        }
      }

      localStorage.setItem('favorites', JSON.stringify(favorites));

      if(this.isFavorite==true){
        // 调用后端 API 更新收藏状态
        axios.post('http://localhost:8081/springboot01/course/getFavorite',
            {
              username: this.username,
              course_id: this.courseId
            },
            {
              headers: {
                'Content-Type': 'application/json'
              }
            })
            .then(response => {
              console.log('Response data:', response.data);
              if (response.data.success || response.data.msg === "请求成功!") {
                Toast.success('收藏成功');
              } else {
                Toast.fail('操作失败');
              }
            })
            .catch(error => {
              console.error('Error:', error);
              Toast.fail('网络请求失败');
            });
      }else{
        axios.post('http://localhost:8081/springboot01/course/deleteFavorite',
            {
              username: this.username,
              course_id: this.courseId
            },
            {
              headers: {
                'Content-Type': 'application/json'
              }
            })
            .then(response => {
              console.log('Response data:', response.data);
              if (response.data.success || response.data.msg === "请求成功!") {
                Toast.success('取消收藏成功');
              } else {
                Toast.fail('操作失败');
              }
            })
            .catch(error => {
              console.error('Error:', error);
              Toast.fail('网络请求失败');
            });


      }
    },
    goTeacher(id) {
      this.$router.push({
        name: 'UpView',
        params: { Id: id }
      });
    },
    checkFavorite(){
      axios.post('http://localhost:8081/springboot01/course/checkFavorite',
          {
            username: this.username,
            course_id: this.courseId,
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            if ( response.data.msg === "请求成功!") {
              console.log('Response data:', response.data);
              this.isFavorite=response.data.data
            } else {
              console.log('Response data:', response.data);
            }
          })
          .catch(error => {
            console.error('Error:', error);
            Toast.fail('网络请求失败');
          });
    },
    submitComment() {
      // 提交评论的方法，可以将评论内容添加到 comments 数组中
      if (this.comment.trim() === '') {
        alert('评论内容不能为空！');
        return;
      }
      const newComment = {
        id: this.comments.length + 1,
        content: this.comment,
        user_head:this.user_head,
        nickname:this.nickname,
      };
      this.comments.unshift(newComment);
      axios.post('http://localhost:8081/springboot01/comment/add',
          {
            username: this.username,
            productId: this.courseId,
            content:  this.comment
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            console.log('Response data:', response.data);
            if ( response.data.msg === "请求成功!") {
              this.comment = '';
              Toast.success('评论成功');
            } else {
              Toast.fail('评论失败');
            }
          })
          .catch(error => {
            console.error('Error:', error);
            Toast.fail('网络请求失败');
          });
    },

    praisel(id,praise){
      if(this.set) {
        axios.post("http://localhost:8081/springboot01/comment/praise", {
              id: id,
              praise:praise,
            }, {
              headers: {
                'Content-Type': 'application/json'
              }
            }
        )
            .then(response => {
              if (response.data.msg=== "请求成功!") {
                this.set=!this.set;
                console.log('Response data:', response.data);
                this.getComment();
              } else {
                console.log('Response data:', response.data);
              }
            })
            .catch(error => {
              console.error('Error:', error);
              Toast.fail('网络请求失败');
            });
      }else {
        axios.post("http://localhost:8081/springboot01/comment/unprsiae", {
              id: id,
              praise:praise,
            }, {
              headers: {
                'Content-Type': 'application/json'
              }
            }
        )
        this.set=!this.set;
        alert("取消点赞成功");
      }
      this.getComment();
    },
    deleteComment(commentId){
      axios.post('http://localhost:8081/springboot01/comment/delete',
          {
            id:commentId,
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            if(response.data.msg === "请求成功!"){
              // 使用 findIndex 方法找到要删除评论在数组中的索引
              const indexToDelete = this.comments.findIndex(comment => comment.id === commentId);

              if (indexToDelete !== -1) {
                this.comments.splice(indexToDelete, 1);
              }

            }

            Toast('删除成功')
          })
          .catch(error => {
            console.error('删除评论失败', error);
          });
    },

    getComment(){
      axios.post('http://localhost:8081/springboot01/comment/list',
          {
            id: this.courseId,
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            this.comments = response.data; // 直接将返回的评论列表赋值给 this.comments
          })
          .catch(error => {
            console.error('获取评论失败', error);
          });
    },
    getmore(){
      axios.post("http://localhost:8081/springboot01/course/getRelatedCourse",
          {
            username:this.username1,
            id:this.courseId,
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            this.others = response.data.data;
          })
          .catch(error => {
            console.error('获取评论失败', error);
          });
    },
    getmyself(){
      axios.post("http://localhost:8081/springboot01/user/getPerson",
          {
            username: this.username1,
          },{
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response=>{
            this.userurl=response.data.data.user_head;
            this.nickname=response.data.data.nickname;
          })
    },

  },
  created() {
    // 获取作者信息
    const userNameJson = localStorage.getItem("user") || '';
    const userNameData = JSON.parse(userNameJson);
    this.username = userNameData.username;
    this.user_head=  userNameData.user_head;
    this.nickname=userNameData.nickname;

    const videosParam = this.$route.query.videos;
    if (videosParam) {
      // 解析并处理传递的数据
      const decodedVideos = JSON.parse(decodeURIComponent(videosParam));
      this.videoUrl = decodedVideos.url;
      this.courseId=decodedVideos.id;
      this.courseName=decodedVideos.courseName;
      this.introduce=decodedVideos.introduce;
      this.lecturerName=decodedVideos.lecturerName;
      this.username1=decodedVideos.username;
      this.playNumber=decodedVideos.playNumber;
      this.commentNumber=decodedVideos.commentNumber;
      this.favoriteNumber=decodedVideos.favoriteNumber;
    }

    this.checkFavorite();
    this.getComment();
    this.getmore();
    this.getmyself();
  }
};
</script>

<style scoped>
.block {
  /*评论消息*/
  margin-bottom: 20px;
  position: relative;
  left: 0px;
}
textarea {
  width: 58%;
  height: 100px;
  resize: vertical;
}
.timestamp{/*评论时间*/
  font-size:10px ;
  margin:auto;
}
.nickname{
  /*  昵称*/
  color: #007bff;
  font-size: 15px;
  position: relative;
  top: 0px;
  left: 50px;
}
.content{
  /*评论*/
  max-height: 20px;
  font-weight:540;
  position: absolute;
  left: 50px;
  width: 700px;
  overflow: auto;
  /*white-space: normal;*/
  /*text-overflow: ellipsis;*/

}
.deleteContent{
  color:#007bff;
  font-size: 10px;
  height: 20px;
  width: 40px;
  border-radius:30%;
  background-color: #ff9bad;
}
.vido{
  position: relative;
  left: 0px;
}
.most{
  /*  整体*/
  position: relative;
  left: 200px;
  width: 1400px;
}
.author{
  /*作者*/
  position: absolute;
  top:50px;
  left: 60%;
}
.momo{
  position: absolute;
  top: 100px;
  left: 60%;
}
.mmmg{
  width: 50px;
  height: 50px;
  border-radius:50%;
  position: absolute;
}
</style>